//
//  MyInfoVC.swift
//  ShareUmbrella
//
//  Created by duanmingyang on 2017/9/16.
//  Copyright © 2017年 尧尚信息科技. All rights reserved.
//

import UIKit
import YSKit
import MBProgressHUD
import SDWebImage

class MyInfoVC:  YSBaseViewController,UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    let kScreenHeight = UIScreen.main.bounds.size.height
    let kScreenWidth = UIScreen.main.bounds.size.width
    var selfTableView:UITableView!
    var dataDic = NSDictionary.init()
    var nicknameLab:UILabel?
    var ageLab:UILabel?
    var sexLab:UILabel?
    var phoneLab:UILabel?
    var headIcon:UIImageView!
    
    var uploadAlertController:UIAlertController!
    var imagePickerController:UIImagePickerController!
    
    let dataArr = ["昵称","年龄","性别","手机号"]
    
    override func setup() {
        super.setup()
    }
    
    /*
     *
     * 界面布局初始化
     */
    override func buildUI() {
        super.buildUI()
        self.title = I18n("VC.usercenter.title")
        
        self.edgesForExtendedLayout = UIRectEdge(rawValue: 0)
        
        self.initBackgourndViewColor()
        self.addSelfTableView()
        self.getUserInfo()
        self.initAlertController()
        self.initImagePickerController()
        
    }
    
    
    //
    override func buildRx() {
        super.buildRx()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        nicknameLab?.text = UserService.sharedInstance.name.value
        ageLab?.text = UserService.sharedInstance.age.value! + "岁"
        sexLab?.text = UserService.sharedInstance.name.value
        phoneLab?.text = UserService.sharedInstance.phone.value
        headIcon.sd_setImage(with: URL(string: UserService.sharedInstance.headLogo.value ?? ""),placeholderImage:  UIImage(named: "空白头像"), options: SDWebImageOptions.highPriority, completed: nil)
        selfTableView.reloadData()
        
    }
    
    //RGB
    func RGB(r:CGFloat,_ g:CGFloat,_ b:CGFloat) -> UIColor{
        return UIColor(red: (r)/255.0, green: (g)/255.0, blue: (b)/255.0, alpha: 1.0)
    }
    
    //初始化背景颜色
    func initBackgourndViewColor() {
        self.view.backgroundColor = RGB(r: 239, 239, 243)
    }
    
    
    //用户信息
    func getUserInfo() {
        _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(UserAPI.userInfo(token: Auth.token))).subscribe(onNext: { [weak self] (data) in
            //
            HUD.hide()
            guard let _ = self else {
                return
            }
            
            guard let userInfo = data else{
                return
            }
            
            self?.dataDic = data!["data"].dictionaryObject! as NSDictionary
            
            UserService.sharedInstance.name.value = userInfo["data"]["nickname"].string ?? ""
            UserService.sharedInstance.age.value = userInfo["data"]["age"].string ?? "0"
            switch userInfo["data"]["sex"].stringValue {
            case "0":
                UserService.sharedInstance.sex.value = .male
            case "1":
                UserService.sharedInstance.sex.value = .female
            default:
                UserService.sharedInstance.sex.value = .unknow
            }
            UserService.sharedInstance.phone.value = userInfo["data"]["phone"].string ?? "0"
            
            self?.selfTableView.reloadData()
            }, onError: { [weak self](ErrorType) in
                HUD.hide()
                guard let  `self` = self else {
                    return
                }
                self.handle(withError: ErrorType)
        })
        
    }
    
    //添加一个tableview
    func addSelfTableView(){
        
        let v = UIView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 80))
        v.backgroundColor = UIColor.clear
        
        let b = UIButton.init(frame: CGRect(x: 0, y: 10, width: kScreenWidth, height: 70))
        b.backgroundColor = UIColor.white
        b.addTarget(self, action: #selector(switchUpdateHeaderImg), for: UIControlEvents.touchUpInside)
        v.addSubview(b)
        
        let titleLabel = UILabel.init()
        titleLabel.backgroundColor = UIColor.clear;
        titleLabel.frame = CGRect(x:15, y:0, width:200, height:70)
        titleLabel.text = "用户头像"
        titleLabel.textColor = RGB(r: 74, 74, 94)
        titleLabel.font = UIFont.systemFont(ofSize: 16)
        b.addSubview(titleLabel)
        
        headIcon = UIImageView.init(frame: CGRect(x: kScreenWidth-85, y: (b.frame.size.height-50)/2, width: 50, height: 50))
        headIcon.layer.cornerRadius = 25
        headIcon.layer.borderColor = UIColor.white.cgColor
        headIcon.clipsToBounds = true;
        headIcon.image = UIImage.init(named: "空白头像")
        b.addSubview(headIcon)
        
        let nextIcon = UIImageView.init(frame: CGRect(x: kScreenWidth-30, y: 25, width: 20, height: 20))
        nextIcon.image = UIImage.init(named: "下一步")
        b.addSubview(nextIcon)
        
        let line = UIView.init(frame: CGRect(x: 15, y: 79.5, width: kScreenWidth, height: 0.5))
        line.backgroundColor = RGB(r: 230, 230, 230)
        v.addSubview(line)
        
        selfTableView = UITableView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight), style: UITableViewStyle.grouped)
        selfTableView.dataSource = self
        selfTableView.delegate = self
        selfTableView.backgroundColor = UIColor.clear
        selfTableView.separatorStyle = UITableViewCellSeparatorStyle.none;
        selfTableView.showsHorizontalScrollIndicator = false
        selfTableView.showsVerticalScrollIndicator = false
        selfTableView.tableHeaderView = v
        self.view.addSubview(selfTableView)
    }
    
    func initImagePickerController()
    {
        self.imagePickerController = UIImagePickerController()
        self.imagePickerController.delegate = self
        // 设置是否可以管理已经存在的图片或者视频
        self.imagePickerController.allowsEditing = true
    }
    
    func initAlertController(){
        weak var blockSelf = self
        self.uploadAlertController = UIAlertController(title:nil, message: nil, preferredStyle:UIAlertControllerStyle.actionSheet)
        //self.uploadAlertController.view.tintColor = UIColor.white
        let takePhoto = UIAlertAction(title:"拍照", style:UIAlertActionStyle.default) { (action:UIAlertAction)in
            blockSelf?.actionAction(action: action)
        }
        let photoLib = UIAlertAction(title:"从相册选择", style:UIAlertActionStyle.default) { (action:UIAlertAction)in
            blockSelf?.actionAction(action: action)
        }
        let cancel = UIAlertAction(title:"取消", style:UIAlertActionStyle.cancel) { (action:UIAlertAction)in
            blockSelf?.actionAction(action: action)
        }
        self.uploadAlertController?.addAction(takePhoto)
        self.uploadAlertController?.addAction(photoLib)
        self.uploadAlertController?.addAction(cancel)
    }
    
    func switchUpdateHeaderImg(){
        self.ys.push(ImagePreviewViewController())
       // present(self.uploadAlertController, animated:true, completion: nil)
    }
    
    func actionAction(action:UIAlertAction)
    {
        if action.title == "拍照" {
            self.getImageFromPhotoLib(type: .camera)
        }else if action.title == "从相册选择" {
            self.getImageFromPhotoLib(type: .photoLibrary)
        }
    }
    
    func getImageFromPhotoLib(type:UIImagePickerControllerSourceType)
    {
        self.imagePickerController.sourceType = type
        //判断是否支持相册
        if (UIImagePickerController.isSourceTypeAvailable(.photoLibrary)) {
            self.present(self.imagePickerController, animated: true, completion:nil)
        }
    }
    
    //MARK:UITableView DataSource
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let iderntify:String = "swiftCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: iderntify) as? MineCell
        if(cell == nil){
            cell=MineCell(style: UITableViewCellStyle.default
                , reuseIdentifier: iderntify);
            
        }
        let row = indexPath.row
        
        let str = dataArr[row]
        
        cell?.titleLabel?.text = str
        
        //nicknameLab?.text = UserService.sharedInstance.name.value
        //agenLab?.text = UserService.sharedInstance.age.value! + "岁"
        //sexLab?.text = UserService.sharedInstance.name.value
       // phoneLab?.text = UserService.sharedInstance.phone.value
        
        if(str == "昵称"){
            nicknameLab = cell?.valueLeb
            nicknameLab?.text = UserService.sharedInstance.name.value
        }else if(str == "年龄"){
            ageLab = cell?.valueLeb
            ageLab?.text = UserService.sharedInstance.age.value! + "岁"
        }else if(str == "性别"){
            sexLab = cell?.valueLeb
            let str = UserService.sharedInstance.sex.value
            if(str == Sex.male){
                sexLab?.text = "男"
            }else if(str == Sex.female){
                sexLab?.text = "女"
            }else{
                sexLab?.text = "未知"
            }
        }else if(str == "手机号"){
            phoneLab = cell?.valueLeb
            phoneLab?.text = UserService.sharedInstance.phone.value
        }
        
        return cell!
    }
    
    //MARK:UITableView Delegate
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selfTableView?.deselectRow(at: indexPath, animated: true)
        
        let row = indexPath.row
        let str = dataArr[row]
        
        if(str == "昵称"){
            //self.revealViewController()!.revealToggle(nil)
            self.ys.push(NicknameVC())
        }else if(str == "年龄"){
            self.ys.push(AgeVC())
        }else if(str == "性别"){
            self.ys.push(SexVC())
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if(section == 0){
            return 0
        }
        return 10
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 20))
        if(section == 0){
            view.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: 0)
        }
        return view
    }
    
    //MARK:- UIImagePickerControllerDelegate
    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
        
        /// chcek if you can return edited image that user choose it if user already edit it(crop it), return it as image
        if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
            
            /// if user update it and already got it , just return it to 'self.imgView.image'
            //self.imgView.image = editedImage
            
            DispatchQueue.main.async {
                self.updateUserHeadPortrait(image: editedImage)
            }
            //self.updateUserHeadPortrait(image: editedImage)
            
            /// else if you could't find the edited image that means user select original image same is it without editing .
        } else if let orginalImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            
            /// if user update it and already got it , just return it to 'self.imgView.image'.
            //self.imgView.image = orginalImage
            DispatchQueue.main.async {
                self.updateUserHeadPortrait(image: orginalImage)
            }
        } 
        else { print ("error") }
        
        //let image:UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
        //self.updateUserHeadPortrait(image: image)
        
        picker.dismiss(animated: true, completion: nil)
        
    }
    
    func imagePickerControllerDidCancel(_ picker:UIImagePickerController){
        picker.dismiss(animated:true, completion:nil)
    }
    
    func updateUserHeadPortrait(image:UIImage){
        _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(UserAPI.updateUserHeader(token: Auth.token, phone: UserService.sharedInstance.phone.value!, imageData: image))).subscribe(onNext: { [weak self] (data) in
            //
            HUD.hide()
            guard self != nil else {
                return
            }
            
            guard let `data` = data else {
                return
            }
            UserService.sharedInstance.headLogo.value = `data`["data"]["avatorUrl"].string
            
            
            }, onError: { [weak self](ErrorType) in
                HUD.hide()
                guard let  `self` = self else {
                    return
                }
                self.handle(withError: ErrorType, targetVC: self)
        })
    }
}
